﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Touch2Like.DAL;
using Touch2Like.Model;
using System.Data;
using System.Collections;
using OpenFlashChart;
using System.Xml;
using System.Web.UI.HtmlControls;

namespace Touch2Like.Web.Customer.Manage
{
    public partial class Reviews : System.Web.UI.Page
    {
        OpenFlashChart.OpenFlashChart chart = new OpenFlashChart.OpenFlashChart();
        OpenFlashChart.OpenFlashChart chartTags = new OpenFlashChart.OpenFlashChart();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (WebUtility.UserGUID == null || WebUtility.UserGUID == "0")
            {
                Response.Clear();
                Response.Write("<script>parent.ResetURL('/Customer/signin.aspx?next=" + Server.UrlEncode("/Customer/Index.aspx") + "');</script>");
                Response.End();
            }

            if (!IsPostBack)
            {
                tb_EndDate.Text = DateTime.Now.ToShortDateString();
                tb_StartDate.Text = DateTime.Today.AddMonths(-1).ToShortDateString();
                runStatistics();
            }
            
        }

        protected void btn_Refresh_Click(object sender, EventArgs e)
        {
            runStatistics();
        }

        void runStatistics()
        {
            QuestionDAL question = new QuestionDAL();
            DataTable dtSet = question.GetByUserGUID(WebUtility.UserGUID);

            if (dtSet.Rows.Count > 0)
            {
                string setid = dtSet.Rows[0]["QuestionSetID"].ToString();
                foreach (DataRow drSet in dtSet.Rows)
                {
                    if (Convert.ToDateTime(tb_EndDate.Text) <= Convert.ToDateTime(drSet["CreateDate"]))
                    {
                        setid = drSet["QuestionSetID"].ToString();
                        break;
                    }
                }

                DataTable dtQuestion = question.GetBySetID(setid);
                dtQuestion.DefaultView.RowFilter = "QuestionType<>'Comment'";
                Repeater_Question.DataSource = dtQuestion.DefaultView.ToTable();
                Repeater_Question.DataBind();

                dtQuestion.DefaultView.RowFilter = "QuestionType='Comment'";
                Repeater_Comment.DataSource = dtQuestion.DefaultView.ToTable();
                Repeater_Comment.DataBind();
            }
            int count = 0;
            ActivityDAL tag = new ActivityDAL();
            DateTime startDate = Convert.ToDateTime(tb_StartDate.Text), endDate = Convert.ToDateTime(tb_EndDate.Text).AddDays(1);
            DataTable dt = tag.GetDateStatistics(WebUtility.UserGUID, "", startDate, endDate,"Touch2Rate");
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    count += Convert.ToInt32(dt.Rows[i]["TouchCount"].ToString());
                }
                lbl_TotalTouch.Text = "TOTAL: " + count;
            }

            ArrayList data1 = new ArrayList();
            List<string> label1 = new List<string>();
            double max = 0;
            for (int i1 = 0; startDate < endDate; startDate = startDate.AddDays(1))
            {
                if (i1 % 5 == 0)
                    label1.Add(FormatShortDate(startDate));
                else
                    label1.Add("");

                double tcount = 0, rcount = 0;
                List<BarStackValue> list = new List<BarStackValue>();
                if (dt.Select("TouchDay='" + FormatDate(startDate) + "'").Length > 0)
                {
                    tcount = Convert.ToDouble(dt.Select("TouchDay='" + FormatDate(startDate) + "'")[0]["TouchCount"]);
                    rcount = Convert.ToDouble(dt.Select("TouchDay='" + FormatDate(startDate) + "'")[0]["ReviewCount"]);
                    //LineDotValue v = new LineDotValue(val);
                    /*v.Tip = FormatDate(startDate);*/
                    BarStackValue rvalue = new BarStackValue(rcount, "#54AEE2");
                    BarStackValue tvalue = new BarStackValue(tcount - rcount, "#999999");
                    list.Add(rvalue);
                    list.Add(tvalue);

                    data1.Add(list);
                    if (tcount > max) max = tcount;
                }
                else
                {
                    data1.Add(0);
                }
                i1 = i1 + 1;
            }

            OpenFlashChart.BarStack bar1 = new BarStack();
            bar1.Values = data1;

            bar1.Tooltip = "#val#/#total#";

            bar1.Set_Key("review", 12);
            bar1.Set_Key("unreview", 12);

            chart.X_Axis.Labels.SetLabels(label1);

            chart.Bgcolor = "#ffffff";
            chart.X_Axis.GridColour = chart.Bgcolor;
            chart.X_Axis.Colour = "#DADADA";
            chart.X_Axis.Offset = false;
            chart.Y_Axis.GridColour = "#F0F0F0";
            chart.Y_Axis.Colour = chart.Bgcolor;//"#DADADA";
            chart.Y_Axis.Offset = false;
            chart.X_Axis.Steps = 5;
            chart.Y_Axis.Steps = 3;

            chart.AddElement(bar1);

            chart.Title = new Title("");
            chart.Title.Style = "{display:none;}";
            int temp1 = Convert.ToInt32(max / 3) + 1;
            chart.Y_Axis.SetRange(0, temp1 * 3, temp1);
            chart.Tooltip = new ToolTip("#val#/#total#");
            chart.Tooltip.Shadow = false;
            chart.Tooltip.Stroke = 1;
            chart.Tooltip.Colour = "#236DC0";
            chart.Tooltip.BodyStyle = "{color:#ffffff;}";
            chart.Tooltip.BackgroundColor = "#3192FF";
            chart.Tooltip.TitleStyle = "{color:#ffffff;}";
            chart.Tooltip.MouseStyle = ToolTipStyle.NORMAL;
            OpenFlashChartControl1.EnableCache = false;
            OpenFlashChartControl1.Chart = chart;
        }

        string FormatDate(DateTime d)
        {
            string year = d.Year.ToString(), month = d.Month.ToString(), day = d.Day.ToString();
            if (d.Month.ToString().Length < 2) month = "0" + d.Month;
            if (d.Day.ToString().Length < 2) day = "0" + d.Day;
            return year + "-" + month + "-" + day;
        }

        string FormatShortDate(DateTime d)
        {
            string year = d.Year.ToString(), month = d.Month.ToString(), day = d.Day.ToString();
            return month + "/" + day;
        }

        protected void Repeater_Question_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem item = e.Item;
            DataRowView view = item.DataItem as DataRowView;

            BindChart(item, view);
        }

        void BindChart(RepeaterItem item, DataRowView view)
        {
            Literal lb_Title = item.FindControl("lb_Title") as Literal;
            Literal lb_Result = item.FindControl("lb_Result") as Literal;

            OpenFlashChartControl chart_Question = item.FindControl("chart_Question") as OpenFlashChartControl;

            OpenFlashChart.OpenFlashChart fchart = new OpenFlashChart.OpenFlashChart();

            DateTime startDate = Convert.ToDateTime(tb_StartDate.Text), endDate = Convert.ToDateTime(tb_EndDate.Text).AddDays(1);

            ArrayList data1 = new ArrayList();
            List<string> label1 = new List<string>();
            double max = 0;

            AnswerDAL answer = new AnswerDAL();
            DataTable dtAnswer = answer.GetByQuestionID(Convert.ToInt32(view["ListID"]), WebUtility.UserGUID, startDate, endDate);

            //OpenFlashChart.BarStack bar1 = new BarStack();

            List<string> answers = new List<string>();
            List<Line> lines = new List<Line>();

            string q = view["Question"].ToString();

            lb_Title.Text = "Question";
            lb_Result.Text = view["Question"].ToString();

            XmlDocument doc = new XmlDocument();

            switch (view["QuestionType"].ToString())
            {
                case "YesNo":
                    answers.Add("yes");
                    answers.Add("no");

                    lines.Add(new Line());
                    lines.Add(new Line());

                    lines[0].Set_Key("yes", 12);
                    lines[1].Set_Key("no", 12);
                    //bar1.Set_Key("yes", 13);
                    //bar1.Set_Key("no", 13);
                    break;
                case "Rate":
                    answers.Add("1");
                    answers.Add("2");
                    answers.Add("3");
                    answers.Add("4");
                    answers.Add("5");

                    lines.Add(new Line());
                    lines.Add(new Line());
                    lines.Add(new Line());
                    lines.Add(new Line());
                    lines.Add(new Line());

                    /*bar1.Set_Key("1", 13);
                    bar1.Set_Key("2", 13);
                    bar1.Set_Key("3", 13);
                    bar1.Set_Key("4", 13);
                    bar1.Set_Key("5", 13);*/
                    lines[0].Set_Key("1", 12);
                    lines[1].Set_Key("2", 12);
                    lines[2].Set_Key("3", 12);
                    lines[3].Set_Key("4", 12);
                    lines[4].Set_Key("5", 12);
                    break;
                case "MultiCheck":
                    doc = new XmlDocument();
                    doc.LoadXml(q);

                    lb_Result.Text = doc.SelectSingleNode("/Q/Question").InnerText;
                    foreach (XmlNode node in doc.SelectNodes("/Q/Item"))
                    {
                        answers.Add(node.InnerText);

                        Line line = new Line();
                        line.Set_Key(node.InnerText, 12);
                        lines.Add(line);
                        //bar1.Set_Key(node.InnerText, 13);
                    }
                    break;
                case "SingleCheck":
                    doc = new XmlDocument();
                    doc.LoadXml(q);

                    lb_Result.Text = doc.SelectSingleNode("/Q/Question").InnerText;
                    foreach (XmlNode node in doc.SelectNodes("/Q/Item"))
                    {
                        answers.Add(node.InnerText);

                        Line line = new Line();
                        line.Set_Key(node.InnerText, 12);
                        lines.Add(line);
                        //bar1.Set_Key(node.InnerText, 13);
                    }
                    break;
            }

            for (int i1 = 0; startDate < endDate; startDate = startDate.AddDays(1))
            {
                if (i1 % 5 == 0)
                    label1.Add(FormatShortDate(startDate));
                else
                    label1.Add("");

                double cvalue = 0;
                List<BarStackValue> list = new List<BarStackValue>();

                for (int i = 0; i < answers.Count; i++)
                {
                    string a = answers[i];

                    if (dtAnswer.Select("TouchDay='" + FormatDate(startDate) + "' and (Answer='" + a + "' or Answer like '" + a + ",%' or Answer like '%," + a + ",%')").Length > 0)
                        cvalue = Convert.ToDouble(dtAnswer.Select("TouchDay='" + FormatDate(startDate) + "' and (Answer='" + a + "' or Answer like '" + a + ",%' or Answer like '%," + a + ",%')")[0]["TouchCount"]);
                    else
                        cvalue = 0;

                    lines[i].Add(cvalue);
                    //list.Add(new BarStackValue(cvalue));
                    if (cvalue > max) max = cvalue;
                }

                //data1.Add(list);

                i1 = i1 + 1;
            }

            /*bar1.Values = data1;

            bar1.Tooltip = "#val#/#total#";

            fchart.AddElement(bar1);*/

            string[] colors = { "#54AEE2", "#ff0000", "#00ffff", "#FFA500", "#0000ff" };
            int c = 0;
            foreach (Line line in lines)
            {
                line.DotStyleType.DotSize = 3;
                line.Width = 3;
                line.Tooltip = "#val#";
                line.Colour = colors[c];
                fchart.AddElement(line);
                c++;
            }

            fchart.X_Axis.Labels.SetLabels(label1);

            fchart.Bgcolor = "#ffffff";
            fchart.X_Axis.GridColour = fchart.Bgcolor;
            fchart.X_Axis.Colour = "#DADADA";
            fchart.X_Axis.Offset = false;
            fchart.Y_Axis.GridColour = "#F0F0F0";
            fchart.Y_Axis.Colour = fchart.Bgcolor;//"#DADADA";
            fchart.Y_Axis.Offset = false;
            fchart.X_Axis.Steps = 5;
            fchart.Y_Axis.Steps = 3;

            fchart.Title = new Title("");
            fchart.Title.Style = "{display:none;}";
            int temp1 = Convert.ToInt32(max / 3) + 1;
            fchart.Y_Axis.SetRange(0, temp1 * 3, temp1);
            fchart.Tooltip = new ToolTip("#val#/#total#");
            fchart.Tooltip.Shadow = false;
            fchart.Tooltip.Stroke = 1;
            fchart.Tooltip.Colour = "#236DC0";
            fchart.Tooltip.BodyStyle = "{color:#ffffff;}";
            fchart.Tooltip.BackgroundColor = "#3192FF";
            fchart.Tooltip.TitleStyle = "{color:#ffffff;}";
            fchart.Tooltip.MouseStyle = ToolTipStyle.NORMAL;
            chart_Question.EnableCache = false;
            chart_Question.Chart = fchart;
        }

        protected void Repeater_Comment_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem item = e.Item;
            DataRowView view = item.DataItem as DataRowView;

            Literal lb_Title = item.FindControl("lb_Title") as Literal;
            Literal lb_Result = item.FindControl("lb_Result") as Literal;
            HtmlGenericControl ifr = item.FindControl("ifr") as HtmlGenericControl;

            DateTime startDate = Convert.ToDateTime(tb_StartDate.Text), endDate = Convert.ToDateTime(tb_EndDate.Text).AddDays(1);

            AnswerDAL answer = new AnswerDAL();
            DataTable dtAnswer = answer.GetListByQuestionID(Convert.ToInt32(view["ListID"]), WebUtility.UserGUID, startDate, endDate);


            lb_Title.Text = view["Question"].ToString();
            lb_Result.Text = "Total: " + dtAnswer.Rows.Count.ToString();
            ifr.Attributes.Add("src", "/Customer/Manage/Comment.aspx?start=" + Server.UrlEncode(tb_StartDate.Text) + "&end=" + Server.UrlEncode(tb_EndDate.Text) + "&questionid=" + view["ListID"].ToString());
        }
    }
}